<?php
namespace App\Common;

use App\Common\WechatHandler;
use App\Common\ValidateHandler;
use App\Models\Member\CodeRecord;
use Overtrue\EasySms\EasySms;
use App\Models\Member\User;
use Auth;
use Config, Log;

class CodeHandler
{
    const REGIST = 1;  // 注册操作
    const LOGIN = 2;   // 登录操作
    const FORGET = 3;  // 忘记密码
    const RESET = 4;   // 重置手机
    const SETPWD = 5;  // 设置密码
    const TRANSFER = 6;  // 转账验证

    /**
     * 获取并判断操作类型操作类型包括 regist login forget reset
     *
     * @param $handlerType 操作类型 
     * @return 返回对象类型或者错误
     */
    private static function getHandlerType($handlerType)
    {
        $type = false;
        switch ($handlerType) {
            case "regist":
                $type = self::REGIST;
                break;
            case "login":
                $type = self::LOGIN;
                break;
            case "forget":
                $type = self::FORGET;
                break;
            case "setpwd":
                $type = self::SETPWD;
                break;
            case "reset":
                $type = self::RESET;
                break;
            case "transfer":
                $type = self::TRANSFER;
                break;
        }
        return $type;
    }

    /**
     * 生成六位随机验证码 并生成验证码记录
     *
     * @param storeId 店铺id
     * @param phone 手机
     * @param handleType 操作类型 string
     * @return 返回随机数
     */
    public static function makeCode($storeId, $phone, $handlerType)
    {
        $handlerType = self::getHandlerType($handlerType);
        if ($handlerType === self::RESET || $handlerType === self::SETPWD || $handlerType === self::TRANSFER) {
            $storeId = Auth::user()->store_id;
        }
        if (!$handlerType) return ['res' => false, 'info' => '操作类型不存在'];
        if (!WechatHandler::checkStore($storeId)) return ['res' => false, 'info' => '店铺不存在'];
        $validatePhone = ValidateHandler::do([0 => [
            'name' => '手机',
            'value' => $phone,
            'func' => 'is_phone'
        ]]);
        if (!$validatePhone['res']) return $validatePhone;

        $checkPhone = self::checkPhone($phone, $handlerType, $storeId);
        if (!$checkPhone['res']) return ['res' => false, 'info' => $checkPhone['info']];

        $code = sprintf("%'.06d", mt_rand(0,999999));
        $codeRecord = new CodeRecord;
        $data = $codeRecord->makeCodeRecord($code, $storeId, $phone, $handlerType);

        if (!$data['res']) return $data;

        $result = self::sendCode($code, $phone);
        if (!$result) return ['res' => false, 'info' => '短信发送失败'];

        return ['res' => true];
    }

    /**
     * 发送验证码
     *
     * @param code 随机验证码 
     * @param phone 手机号
     * @return 返回结果 array
     */
    private static function sendCode($code, $phone)
    {
        try {
            $config = Config::get("sms");
            $easySms = new EasySms($config);
            $easySms->send($phone, [
                'template' => 'SMS_484050247',
                'data' => [
                    'code' => $code
                ],
            ]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 判断验证码
     *
     * @param code 随机验证码 
     * @param target 操作对象 手机或者邮箱号码
     * @param targetType 操作对象类型 email phone
     * @param handleType 操作类型 1 2 3 绑定 注册  重置
     * @return 返回结果 true false
     */
    public static function checkCode($storeId, $phone, $code, $handlerType)
    {
        if (!WechatHandler::checkStore($storeId)) return ['res' => false, 'info' => '店铺不存在'];

        $handlerType = self::getHandlerType($handlerType);
        $c = CodeRecord::where('type',$handlerType)
                         ->where('expire_at','>=',date('Y-m-d H-i-s'))
                         ->where('phone', $phone)
                         ->where('store_id', $storeId)
                         ->where('code', $code)
                         ->count();

        if ($c > 0) return ['res' => true];

        return ['res' => false, 'info' => '验证码无效'];
    }

    public static function checkPhone($phone, $handlerType, $storeId)
    {
        $arr = ['res' => true];
        $c = User::where('store_id', $storeId)
                  ->where('phone', $phone)
                  ->count();
        switch ($handlerType) {
        case self::REGIST:
                break;
        case self::LOGIN:
                if ($c == 0) {
                    $arr['res'] = false;
                    $arr['info'] = '手机号码不存在';
                }
                break;
        case self::FORGET:
                if ($c == 0) {
                    $arr['res'] = false;
                    $arr['info'] = '手机号码不存在';
                }
                break;
        case self::SETPWD:
                if ($c == 0) {
                    $arr['res'] = false;
                    $arr['info'] = '手机号码不存在';
                }
                break;
        case self::RESET:
                if ($c > 0) {
                    $arr['res'] = false;
                    $arr['info'] = '此手机已绑定';
                }
                break;
        case self::TRANSFER:
                if ($c == 0) {
                    $arr['res'] = false;
                    $arr['info'] = '手机号码不存在';
                }
                break;
        }
        return $arr;
    }
}
